# rm(list = ls())
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(leaflet)
library(rgdal)
## Loading required package: sp
## rgdal: version: 1.1-10, (SVN revision 622)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
##  Path to GDAL shared files: /usr/share/gdal/1.11
##  Loaded PROJ.4 runtime: Rel. 4.8.0, 6 March 2012, [PJ_VERSION: 480]
##  Path to PROJ.4 shared files: (autodetected)
##  Linking to sp version: 1.2-3
library(tigris)
## 
## Attaching package: 'tigris'
## The following object is masked from 'package:graphics':
## 
##     plot
library(RColorBrewer)
library(ggplot2)
library(readr)
# source('fte_theme.R')

county_counts <- read_csv('data/population.csv')

downloaddir<-getwd()
unzip('data/PA_Counties_clip.shp.zip', exdir=downloaddir, junkpaths=TRUE)

filename<-list.files(downloaddir, pattern=".shp", full.names=FALSE)
filename<-gsub(".shp", "", filename[1])

county_shapes<-readOGR(downloaddir, filename) 
## OGR data source with driver: ESRI Shapefile 
## Source: "/home/chris/Dropbox/Chris Tufts/GeneralNotes/Map Talk/example_scripts/leaflet_demo_R", layer: "PA_Counties_clip"
## with 67 features
## It has 13 fields
pal <- colorNumeric(
  palette = "YlGn",
  domain = county_counts$total_pop
)

county_shapes <- geo_join(county_shapes, county_counts, by_sp="NAME" , by_df="NAME" )


# create map 
paHealth.map <- leaflet() %>%
  addProviderTiles('CartoDB.Positron') %>%
  setView(lng=-77.16048, lat=41.00000, zoom =7) %>%
  addPolygons(data = county_shapes,
              stroke = T, smoothFactor = 0.2, fillOpacity = 0.5,
              color = "#000000", weight = 2, 
              fillColor = ~pal(county_shapes$total_pop)
              # color = ~pal(states@data$DISTRICT_)
  )%>% 
  addLegend("bottomright", pal = pal, values = county_counts$total_pop,
            title = "County Population",
            opacity = 1
  )

paHealth.map